package pe.com.hatunsol.hatun_android;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.Gson;

import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import pe.com.hatunsol.hatun_android.dialogframent.ProgressDialogFragment;
import pe.com.hatunsol.hatun_android.entity.ProveedorLocal;
import pe.com.hatunsol.hatun_android.entity.RestResult;
import pe.com.hatunsol.hatun_android.model.ListProveedorLocal;
import pe.com.hatunsol.hatun_android.rest.PostExecuteCallback;
import pe.com.hatunsol.hatun_android.rest.PreExecuteCallback;
import pe.com.hatunsol.hatun_android.rest.RestClient;
import pe.com.hatunsol.hatun_android.rest.RestTask;
import pe.com.hatunsol.hatun_android.utilitario.Util;

/**
 * Created by Sistemas on 09/03/2015.
 */

public class EstablecimientosCercanos extends ActionBarActivity implements OnMapReadyCallback {
    private SupportMapFragment supportBarFragment;
    private GoogleMap googlemap;
    private ProgressDialogFragment mProgressDialogFragment;
    private List<ProveedorLocal> lstProveedorLocal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.establecimientos_cercanos);

        // cargarEstablecimientos();
        new ListaProveedorLocalAsyncTask().execute();

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        this.googlemap = googleMap;
        googlemap.clear();
        //-12.087154,-77.049477
        ProveedorLocal pl;
        LatLng latLng;
        for (int i = 0; i < lstProveedorLocal.size(); i++) {

            pl = lstProveedorLocal.get(i);
            if (pl.getLatitud().equals("") || pl.getLongitud().equals(""))
                continue;
            latLng = new LatLng(Double.parseDouble(pl.getLatitud()), Double.parseDouble(pl.getLongitud()));
            MarkerOptions markeroptions = new MarkerOptions();
            markeroptions.position(latLng);
            markeroptions.title(pl.getNombreComercial());
            markeroptions.flat(true);
            markeroptions.snippet(pl.getDireccion());
            googlemap.addMarker(markeroptions);

        }

        googlemap.getUiSettings().setZoomControlsEnabled(true);
        googlemap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();
        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);
        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);
        if (location == null) {
            latLng = new LatLng(-12.048042, -77.043683);
            googlemap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12), 1500, null);
        } else {
            //onLocationChanged(location);
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            googlemap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12), 1500, null);
        }


        googlemap.getUiSettings().setZoomControlsEnabled(true);


    }

    private void onLocationChanged(Location location) {
       /* // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        googlemap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));*/
    }


    class ListaProveedorLocalAsyncTask extends AsyncTask<Void, Void, RestResult> {

        @Override
        protected void onPostExecute(RestResult restResult) {
            super.onPostExecute(restResult);
            mProgressDialogFragment.dismissAllowingStateLoss();
            //Log.d("statusCode", restResult.getStatusCode() + "");
            //Log.d("result",restResult.getResult()+"");


            try {
                JSONObject jsonobj = new JSONObject(restResult.getResult());
                JSONArray jsonArray = jsonobj.getJSONArray("ListarResult");
                JSONObject jso;
                ProveedorLocal proveedorLocal;
                lstProveedorLocal = new ArrayList<ProveedorLocal>();
                for (int i = 0; i < jsonArray.length(); i++) {
                    jso = jsonArray.getJSONObject(i);
                    proveedorLocal = new ProveedorLocal(jso.getString("_Direccion"), jso.getInt("_IdSupervisor"), jso.getInt("_LocalId")
                            , jso.getString("_NombreComercial"), jso.getInt("_ProveedorId"), jso.getInt("_ProveedorLocalId"), jso.getString("_RUC")
                            , jso.getString("_ProveedorNombre"), jso.getString("_Latitud"), jso.getString("_Longitud"));
                    lstProveedorLocal.add(proveedorLocal);
                }
                supportBarFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragMap);
                supportBarFragment.getMapAsync(EstablecimientosCercanos.this);

            } catch (JSONException e) {
                e.printStackTrace();
            }


        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialogFragment = new ProgressDialogFragment();
            mProgressDialogFragment.setMensaje("Cargando Establecimientos..");
            mProgressDialogFragment.show(getFragmentManager(), ProgressDialogFragment.TAG);
        }

        @Override
        protected RestResult doInBackground(Void... params) {
            StringEntity stringEntity = null;
            return new RestClient().get("ProveedorLocal.svc/ProveedorLocal?cargoid=0&empleadoid=0&localid=0&nombreproveedor=", stringEntity, 10000);
        }
    }


}
